package com.cqcet.wenchuang.handler;

import com.cqcet.wenchuang.common.R;
import com.cqcet.wenchuang.common.customException.CustomException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器，接收controller层抛出的异常，处理后返回消息给前端程序
 * @author 86173
 */
@RestControllerAdvice(annotations = {RestController.class, Controller.class})
public class GlobalExceptionHandler {

    /**
     * 唯一约束异常
     * @param e
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException e) {
        //包含了唯一约束异常
        if (e.getMessage().contains("Duplicate entry")) {
            String[] strings = e.getMessage().split(" ");
            String msg = strings[2] + "已存在";
            return R.error(msg);
        }
        //发生了未知的异常
        return R.error("未知错误");
    }

    /**
     * 自定义业务异常
     * @param e
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException e) {
        return R.error(e.getMessage());
    }
}
